package com.cxlin.base.bottomtab

import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.cxlin.base.BaseActivity
import com.cxlin.base.R
import com.cxlin.base.databinding.ActivityBottomTabBinding

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/4/25 10:11
 */
abstract class BottomTabActivity : BaseActivity() {

    private val binding: ActivityBottomTabBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_bottom_tab)
    }

    override fun initView(savedInstanceState: Bundle?) {
        binding.viewPager.isUserInputEnabled = false
        binding.viewPager.offscreenPageLimit = 2
        binding.viewPager.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = getMenus().size

            override fun createFragment(position: Int): Fragment = getFragments().get(position)

        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        binding.navView.menu.clear()
        getMenus().forEach {
            binding.navView.menu.add(it.groupId, it.itemId, it.order, it.title)
            binding.navView.menu.findItem(it.itemId).icon = ContextCompat.getDrawable(this@BottomTabActivity,it.iconId)
        }
        binding.navView.itemIconTintList

        binding.navView.setOnItemSelectedListener {
            val item = it
            for ((index, value) in getMenus().withIndex()) {
                if (value.itemId == item.itemId) {
                    switchFragment(index)
                    break
                }
            }
            true
        }
    }

    private fun switchFragment(position: Int): Boolean {
        binding.viewPager.setCurrentItem(position, false)
        return true
    }

    abstract fun getMenus(): List<MenuBean>
    abstract fun getFragments(): List<Fragment>
}